package net.xdclass.xdclassmq.jms.producer;

import net.xdclass.xdclassmq.config.RocketMqConfig;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * @Author whg
 * @create 2022/12/15 14:45
 * @description：
 */
@Component
public class OrderProducer {

    @Autowired
    private RocketMqConfig rocketMqConfig;

    private static volatile DefaultMQProducer producer = null;

    public OrderProducer(){
    }

    public DefaultMQProducer getProducer(){
        if(null == producer){
            synchronized(OrderProducer.class){
                producer = new DefaultMQProducer(rocketMqConfig.getProducerGroup());
                producer.setNamesrvAddr(rocketMqConfig.getNameServerAddr());
                producer.setRetryTimesWhenSendFailed(3);
                start();
            }
        }
        return producer;
    }

    /**
     * 对象在使用之前必须要调用一次，只能初始化一次
     */
    private void start(){
        try{
            this.producer.start();
        }catch (MQClientException e){
            e.printStackTrace();
        }
    }

    /**
     * 一般在应用上下文，使用上下文监听器，进行关闭
     */
    private @PreDestroy void shutdown(){
        this.producer.shutdown();
    }


}
